package com.atguigu.ssyx.acl.service.Impl;

import com.atguigu.ssyx.acl.Utils.PermissionHelper;
import com.atguigu.ssyx.acl.mapper.PermissionMapper;
import com.atguigu.ssyx.acl.service.PermissionService;
import com.atguigu.ssyx.common.result.Result;
import com.atguigu.ssyx.model.acl.Permission;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements PermissionService {

    @Override
    public List<Permission> queryAllMenu() {
        List<Permission> permissions = baseMapper.selectList(null);
        List<Permission> permissions1 = PermissionHelper.buildPermission(permissions);
        return permissions1;
    }


    @Override
    public void removeChildById(Long id) {
//        获得所有菜单项数据
        List<Permission> permissions = baseMapper.selectList(null);

//        需要删除的节点
        List<Long> array = new ArrayList();

        getNodeChild(id, array, permissions);
        array.add(id);
//        根据父id,判断出其他节点的pid.相等就是子节点.
        baseMapper.deleteBatchIds(array);
    }

    /**
     * 递归获取子节点
     *
     * @param id
     * @param
     */
    public void getNodeChild(Long id, List<Long> array, List<Permission> permissions) {
//找到子节点.
        permissions.stream().forEach(permission -> {
            if (permission.getPid().equals(id)) {
                array.add(permission.getId());
                getNodeChild(permission.getId(), array, permissions);
            }
        });
    }
}
